package com.laundry.service.impl;

import com.laundry.dao.UserDao;
import com.laundry.dto.LoginDTO;
import com.laundry.dto.ResultDTO;
import com.laundry.entity.User;
import com.laundry.service.UserService;
import com.laundry.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    
    @Autowired
    private UserDao userDao;
    
    @Override
    public ResultDTO login(LoginDTO loginDTO) {
        User user = userDao.findByUsername(loginDTO.getUsername());
        if (user == null) {
            return ResultDTO.error("用户不存在");
        }
        
        // 验证密码
        if (!MD5Util.verify(loginDTO.getPassword(), user.getPassword())) {
            return ResultDTO.error("密码错误");
        }
        
        return ResultDTO.success(user);
    }
    
    @Override
    public ResultDTO register(User user) {
        // 检查用户名是否存在
        User existUser = userDao.findByUsername(user.getUsername());
        if (existUser != null) {
            return ResultDTO.error("用户名已存在");
        }
        
        // 打印接收到的用户信息
        System.out.println("接收到的用户信息: " + user); // 调试信息
        
        // 加密密码
        if (user.getPassword() == null || user.getPassword().isEmpty()) {
            System.out.println("接收到的密码为空"); // 调试信息
            return ResultDTO.error("密码不能为空");
        }
        System.out.println("接收到的密码: " + user.getPassword()); // 调试信息
        user.setPassword(MD5Util.encrypt(user.getPassword()));
        user.setIsAdmin(false);
        userDao.save(user);
        
        return ResultDTO.success();
    }
    
    @Override
    public ResultDTO getUserInfo(Long userId) {
        User user = userDao.findById(userId).orElse(null);
        if (user == null) {
            return ResultDTO.error("用户不存在");
        }
        
        return ResultDTO.success(user);
    }
    
    @Override
    public ResultDTO updateUserInfo(User user) {
        User existUser = userDao.findById(user.getId()).orElse(null);
        if (existUser == null) {
            return ResultDTO.error("用户不存在");
        }
        
        // 不更新密码和管理员标志
        user.setPassword(existUser.getPassword());
        user.setIsAdmin(existUser.getIsAdmin());
        
        userDao.save(user);
        
        return ResultDTO.success();
    }
    
    @Override
    public List<User> getAllUsers() {
        return userDao.findAll();
    }
    
    @Override
    public void deleteUser(Long userId) {
        userDao.deleteById(userId);
    }
} 